package com.maxd.modules.antPlant.schedule;
import com.maxd.controller.order.OrderTask;
import com.maxd.modules.antPlant.api.resp.*;
import com.maxd.modules.antPlant.api.resp.WphOrderQueryResp.Data.OrderinfolistItem.DetaillistItem;
import com.maxd.modules.antPlant.api.resp.FoodOrderQueryResp.Data.ListItem.GoodsdataItem;
import com.google.common.collect.Lists;

import com.maxd.model.PublisherOrderDtoBean;
import com.maxd.model.UserInfo;
import com.maxd.modules.antPlant.api.AntPlanetComplexApi;
import com.maxd.respository.order.OrderJpaRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author mengshx
 * datetime 2024-04-13 18:34
 **/
@Slf4j
@Component
public class AntPlanetTask {
    @Autowired
    AntPlanetComplexApi antPlanetComplexApi;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderJpaRepository orderJpaRepository;
    @Autowired
    private OrderTask orderTask;
    ExecutorService service = Executors.newFixedThreadPool(3);

    @Scheduled(fixedDelay = 120 * 1000)
    void synOnceDuoMaiOrder() {
        service.execute(() -> {
            syncAntPlanetRechargeOrder();
            syncAntPlanetMovieOrder();
            syncAntPlanetFoodOrder();
            syncAntPlanetWphOrder();
            syncAntPlanetZhoubyhOrder();
            syncAntPlanetOtherOrder();
        });
    }

    /**
     * author mengshx
     * 其他订单
     * datetime 2024/4/28 17:16 2024/4/28
     * @throws
     **/
    public void syncAntPlanetOtherOrder() {
        DecimalFormat df = new DecimalFormat("#########.##");
        Calendar cal = Calendar.getInstance();
        //此时此刻
        Date now = cal.getTime();
        //定位到昨天的零点
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, -18);
        //昨天
        Date yesterday = cal.getTime();

        Integer page = 1;
        Integer pageSize = 20;

        OtherOrderQueryResp resp = null;

        do {
            resp = antPlanetComplexApi.queryOtherOrder(page, pageSize, yesterday, now, null);
            OtherOrderQueryResp.Data data = resp.getData();
            List<OtherOrderQueryResp.Data.DataItem> list = data.getData();
            list.forEach((item) -> {
                String id = item.getId();
                Integer pfType = item.getPfType();
                String uid = item.getExtendId();
                String parentid = item.getParentid();
                String orderid = item.getOrderid();
                Integer ordertime = item.getOrdertime();
                Integer finishtime = item.getFinishtime();
                String goodsId = item.getGoodsId();
                String goodsName = item.getGoodsName();
                String picurl = item.getPicurl();
                String goodsNum = item.getGoodsNum();
                Integer cosprice = item.getCosprice();
                Integer commission = item.getCommission();
                Integer commissionrate = item.getCommissionrate();
                String valistatus = item.getValistatus();
                String validcode = item.getValidcode();
                Integer yn = item.getYn();
                Integer isbalance = item.getIsbalance();
                UserInfo userInfo = fetchUser(uid);
                PublisherOrderDtoBean o = fetchOrder(orderid);
                if (o.getId() == null) {
                    o.setFromInfo("antplanet");
                    o.setIsJifen(0);
                    o.setIsGif(0);
                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                    o.setBalance(0);
                    if(userInfo!=null){
                        o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                        o.setInvitation(userInfo.getInvitation());
                    }
                    o.setAdzone_id(109264550298L);
                    o.setAdzone_name(Config.BASE_NAME);
                    o.setOrder_type(item.getTypeName());
                    o.setItem_num(Integer.valueOf(goodsNum));
                    //商品图片
//                o.setItem_img(goodsImg);
//                //商品标题
                    o.setItem_title(goodsName);
//                //订单编号
                    o.setTrade_id(orderid);
                    o.setTrade_parent_id(orderid);
                //商品id
                    o.setItem_id("0");
//                //单个商品金额
                    o.setItem_price(df.format(cosprice.floatValue()/100));
//                //设置佣金金额
                    o.setPub_share_pre_fee(df.format(commission.floatValue()/100));
//                //实际支付金额
                    o.setAlipay_total_price(df.format((cosprice.floatValue()-commission.floatValue())/100));
//                //订单支付时间
                    o.setTb_paid_time(DateFormatUtils.format(ordertime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //订单支付时间
                    o.setTk_paid_time(DateFormatUtils.format(ordertime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //处理订单状态3已结算12已付款13已失效
                    o.setTk_status(12);//处理已付款状态
                    //蚂蚁星球订单佣金结算状态0否1是
//                "status":,//状态 0-待付款，1-已付款，2-已付款充值中 ，3-充值完成，5-已结算10-订单关闭
                }else {
                    o.setTb_paid_time(DateFormatUtils.format(ordertime*1000l,"yyyy-MM-dd HH:mm:ss"));
                    o.setTk_paid_time(DateFormatUtils.format(ordertime*1000l,"yyyy-MM-dd HH:mm:ss"));

                    if(!o.getPub_share_pre_fee().equals(String.valueOf(df.format(commission.floatValue()/100))) && userInfo!=null){
                        o.setPub_share_pre_fee(df.format(commission.floatValue()/100));
                        orderTask.getRate(o,userInfo, commission.floatValue()/100,df,null);
                    }
                    //处理订单状态 这里处理已付款状态
                    if (isbalance.equals(1)) {
                        //已结算
                        o.setTk_status(3);
                    }else if(yn.equals(0)){
                        ////已结算无效
                        o.setTk_status(13);
                    }
                }

                orderJpaRepository.save(o);

            });
            page++;
        } while (resp != null && (pageSize*(page-1))<resp.getData().getTotal());

    }

    /**
     * author mengshx
     * 周边优惠
     * datetime 2024/4/28 16:42 2024/4/28
     * @throws
     **/
    private void syncAntPlanetZhoubyhOrder() {
        DecimalFormat df = new DecimalFormat("#########.##");
        Calendar cal = Calendar.getInstance();
        //此时此刻
        Date now = cal.getTime();
        //定位到昨天的零点
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, -18);
        //昨天
        Date yesterday = cal.getTime();

        Integer page = 1;
        Integer pageSize = 20;

        ZhoubyhOrderQueryResp resp = null;

//        do {
//            resp = antPlanetComplexApi.queryZhoubyhOrder(page, pageSize, yesterday, now);
//            ZhoubyhOrderQueryResp.Data data = resp.getData();
//            List<ZhoubyhOrderQueryResp.Data.ListItem> list = data.getList();
//            list.forEach(item -> {
//                //推广id
//                String uid = item.getUid();
//                //订单id
//                String orderid = item.getOrderid();
//                String refundid = item.getRefundid();
//                Integer status = item.getStatus();
//                String isbalance = item.getIsbalance();
//                String statusstr = item.getStatusstr();
//                Integer payprice = item.getPayprice();
//                Integer price = item.getPrice();
//                Integer realNum = item.getRealNum();
//                Integer returnPrice = item.getReturnPrice();
//                Integer commission = item.getCommission();
//                Integer goodsId = item.getGoodsId();
//                String goodsName = item.getGoodsName();
//                String rechargeno = item.getRechargeno();
//                String goodsNum = item.getGoodsNum();
//                String province = item.getProvince();
//                Integer closetime = item.getClosetime();
//                String closetxt = item.getClosetxt();
//                Integer createdtime = item.getCreatedtime();
//                Integer completetime = item.getCompletetime();
//                Integer updatedtime = item.getUpdatedtime();
//                UserInfo userInfo = fetchUser(uid);
//                PublisherOrderDtoBean o = fetchOrder(orderid);
//                if (o.getId() == null) {
//                    o.setFromInfo("antplanet");
//                    o.setIsJifen(0);
//                    o.setIsGif(0);
//                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
//                    o.setBalance(0);
//                    if(userInfo!=null){
//                        o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
//                        o.setInvitation(userInfo.getInvitation());
//                    }
//                    o.setAdzone_id(109264550298L);
//                    o.setAdzone_name(Config.BASE_NAME);
//                    o.setOrder_type("蚂蚁星球");
//                    o.setItem_num(Integer.valueOf(goodsNum));
//                    //商品图片
////                o.setItem_img(goodsImg);
////                //商品标题
//                    o.setItem_title(goodsName);
////                //订单编号
//                    o.setTrade_id(orderid);
//                    o.setTrade_parent_id(orderid);
////                //商品id
//                    o.setItem_id(String.valueOf(goodsId));
////                //单个商品金额
//                    o.setItem_price(df.format(price.floatValue()/100));
////                //设置佣金金额
//                    o.setPub_share_pre_fee(df.format(commission.floatValue()/100));
////                //实际支付金额
//                    o.setAlipay_total_price(df.format(payprice.floatValue()/100));
////                //订单支付时间
//                    o.setTb_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
////                //订单支付时间
//                    o.setTk_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
////                //处理订单状态3已结算12已付款13已失效
//                    o.setTk_status(12);//处理已付款状态
//                    //蚂蚁星球订单佣金结算状态0否1是
////                "status":,//状态 0-待付款，1-已付款，2-已付款充值中 ，3-充值完成，5-已结算10-订单关闭
//                }else {
//                    o.setTb_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                    o.setTk_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//
//                    if(!o.getPub_share_pre_fee().equals(String.valueOf(commission)) && userInfo!=null){
//                        o.setPub_share_pre_fee(String.valueOf(commission));
//                        orderTask.getRate(o,userInfo, Float.parseFloat(String.valueOf(commission)),df,null);
//                    }
//                    //处理订单状态 这里处理已付款状态
//                    if (status.equals(1)) {
//                        o.setTk_status(12);
//                    }else if(status.equals(5)){
//                        o.setTk_status(3);
//                    }else if(status.equals(10)){
//                        o.setTk_status(13);
//                    }
//                }
//
//                orderJpaRepository.save(o);
//
//            });
//
//            page++;
//        } while (resp != null && !resp.getData().getFinish());


    }

    /**
     * author mengshx
     * 同步充值订单查询
     * datetime 2024/4/14 18:29 2024/4/14
     *
     * @throws
     **/
    public void syncAntPlanetRechargeOrder() {
        DecimalFormat df = new DecimalFormat("#########.##");
        Calendar cal = Calendar.getInstance();
        //此时此刻
        Date now = cal.getTime();
        //定位到昨天的零点
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, -18);
        //昨天
        Date yesterday = cal.getTime();

        Integer page = 1;
        Integer pageSize = 20;

        RechargeOrderQueryResp resp = null;

        do {
            resp = antPlanetComplexApi.queryRechargeOrder(page, pageSize, yesterday, now, null, null, null, null);
            RechargeOrderQueryResp.Data data = resp.getData();
            List<RechargeOrderQueryResp.Data.ListItem> list = data.getList();
            list.forEach(item -> {
                //推广id
                String uid = item.getUid();
                //订单id
                String orderid = item.getOrderid();
                String refundid = item.getRefundid();
                Integer status = item.getStatus();
                String isbalance = item.getIsbalance();
                String statusstr = item.getStatusstr();
                Integer payprice = item.getPayprice();
                Integer price = item.getPrice();
                Integer realNum = item.getRealNum();
                Integer returnPrice = item.getReturnPrice();
                Integer commission = item.getCommission();
                Integer goodsId = item.getGoodsId();
                String goodsName = item.getGoodsName();
                String rechargeno = item.getRechargeno();
                String goodsNum = item.getGoodsNum();
                String province = item.getProvince();
                Integer closetime = item.getClosetime();
                String closetxt = item.getClosetxt();
                Integer createdtime = item.getCreatedtime();
                Integer completetime = item.getCompletetime();
                Integer updatedtime = item.getUpdatedtime();
                UserInfo userInfo = fetchUser(uid);
                PublisherOrderDtoBean o = fetchOrder(orderid);
                if (o.getId() == null) {
                    o.setFromInfo("antplanet");
                    o.setIsJifen(0);
                    o.setIsGif(0);
                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                    o.setBalance(0);
                    if(userInfo!=null){
                        o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                        o.setInvitation(userInfo.getInvitation());
                    }
                    o.setAdzone_id(109264550298L);
                    o.setAdzone_name(Config.BASE_NAME);
                    o.setOrder_type("蚂蚁星球");
                    o.setItem_num(Integer.valueOf(goodsNum));
                    //商品图片
//                o.setItem_img(goodsImg);
//                //商品标题
                    o.setItem_title(goodsName);
//                //订单编号
                    o.setTrade_id(orderid);
                    o.setTrade_parent_id(orderid);
//                //商品id
                    o.setItem_id(String.valueOf(goodsId));
//                //单个商品金额
                    o.setItem_price(df.format(price.floatValue()/100));
//                //设置佣金金额
                    o.setPub_share_pre_fee(df.format(commission.floatValue()/100));
//                //实际支付金额
                    o.setAlipay_total_price(df.format(payprice.floatValue()/100));
//                //订单支付时间
                    o.setTb_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //订单支付时间
                    o.setTk_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //处理订单状态3已结算12已付款13已失效
                    o.setTk_status(12);//处理已付款状态
                    //蚂蚁星球订单佣金结算状态0否1是
//                "status":,//状态 0-待付款，1-已付款，2-已付款充值中 ，3-充值完成，5-已结算10-订单关闭
                }else {
                    o.setTb_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
                    o.setTk_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));

                    if(!o.getPub_share_pre_fee().equals(String.valueOf(commission)) && userInfo!=null){
                        o.setPub_share_pre_fee(df.format(commission.floatValue()/100));
                        orderTask.getRate(o,userInfo, Float.parseFloat(String.valueOf(commission))/100,df,null);
                    }
                    //处理订单状态 这里处理已付款状态
                    if (status.equals(1)) {
                        o.setTk_status(12);
                    }else if(status.equals(5)){
                        o.setTk_status(3);
                    }else if(status.equals(10)){
                        o.setTk_status(13);
                    }
                }

                orderJpaRepository.save(o);

            });

            page++;
        } while (resp != null && !resp.getData().getFinish());


    }
    /**
     * author mengshx
     * 同步电影票订单查询
     * @throws
     **/
    public void syncAntPlanetMovieOrder() {
        DecimalFormat df = new DecimalFormat("#########.##");
        Calendar cal = Calendar.getInstance();
        //此时此刻
        Date now = cal.getTime();
        //定位到昨天的零点
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, -1);
        //昨天
        Date yesterday = cal.getTime();

        Integer page = 1;
        Integer pageSize = 20;

        MovieOrderQueryResp resp = null;

        do {
            resp = antPlanetComplexApi.queryMovieOrder(page, pageSize, yesterday, now, null, null, null);
            MovieOrderQueryResp.Data data = resp.getData();
            List<MovieOrderQueryResp.Data.ListItem> list = data.getList();
                        list.forEach(item -> {
                            String uid = item.getUid();
                            String showid = item.getShowid();
                            String orderid = item.getOrderid();
                            String refundid = item.getRefundid();
                            Integer status = item.getStatus();
                            String isbalance = item.getIsbalance();
                            Integer payprice = item.getPayprice();
                            Integer price = item.getPrice();
                            Integer commission = item.getCommission();
                            List<String> seat = item.getSeat();
                            Integer model = item.getModel();
                            String seatid = item.getSeatid();
                            String seatno = item.getSeatno();
                            String realseat = item.getRealseat();
                            String ordernum = item.getOrdernum();
                            Integer tickettime = item.getTickettime();
                            Integer closetime = item.getClosetime();
                            String closetxt = item.getClosetxt();
                            Integer acceptseat = item.getAcceptseat();
                            List<String> info = item.getInfo();
                            String stopselltime = item.getStopselltime();
                            String createdtime = item.getCreatedtime();
                            String updatedtime = item.getUpdatedtime();
                            Integer discountsprice = item.getDiscountsprice();
                UserInfo userInfo = fetchUser(uid);
                PublisherOrderDtoBean o = fetchOrder(orderid);
                if (o.getId() == null) {
                    o.setFromInfo("antplanet");
                    o.setIsJifen(0);
                    o.setIsGif(0);
                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                    o.setBalance(0);
                    if(userInfo!=null){
                        o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                        o.setInvitation(userInfo.getInvitation());
                    }
                    o.setAdzone_id(109264550298L);
                    o.setAdzone_name(Config.BASE_NAME);
                    o.setOrder_type("蚂蚁星球");
                    o.setItem_num(1);
                    //商品图片
//                o.setItem_img(goodsImg);
//                //商品标题
                    o.setItem_title(StringUtils.join(info));
//                //订单编号
                    o.setTrade_id(orderid);
                    o.setTrade_parent_id(orderid);
//                //商品id
                    o.setItem_id(String.valueOf(Integer.valueOf(showid)));
//                //单个商品金额
                    o.setItem_price(df.format(price.floatValue()/100));
//                //设置佣金金额
                    o.setPub_share_pre_fee(df.format(commission.floatValue()/100));
//                //实际支付金额
                    o.setAlipay_total_price(df.format(payprice.floatValue()/100));
//                //订单支付时间
                    o.setTb_paid_time(createdtime);
//                //订单支付时间
                    o.setTk_paid_time(createdtime);
//                //处理订单状态3已结算12已付款13已失效
                    o.setTk_status(12);//处理已付款状态
                    //蚂蚁星球订单佣金结算状态0否1是
//                "status":,//状态 0-待付款，1-已付款，2-已付款充值中 ，3-充值完成，5-已结算10-订单关闭
                }else {
                    if(!o.getPub_share_pre_fee().equals(String.valueOf(commission)) && userInfo!=null){
                        o.setPub_share_pre_fee(String.valueOf(commission));
                        orderTask.getRate(o,userInfo, Float.parseFloat(String.valueOf(commission)),df,null);
                    }
                    //处理订单状态 这里处理已付款状态
                    if (status.equals(1)) {
                        o.setTk_status(12);
                    }else if(status.equals(5)){
                        o.setTk_status(3);
                    }else if(status.equals(10)){
                        o.setTk_status(13);
                    }
                }

                orderJpaRepository.save(o);

            });

            page++;
        } while (resp != null && !resp.getData().getFinish());


    }
    /**
     * author mengshx
     * 同步订餐订单查询
     * datetime 2024/4/14 18:29 2024/4/14
     *
     * @throws
     **/
    public void syncAntPlanetFoodOrder() {
        DecimalFormat df = new DecimalFormat("#########.##");
        Calendar cal = Calendar.getInstance();
        //此时此刻
        Date now = cal.getTime();
        //定位到昨天的零点
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, -1);
        //昨天
        Date yesterday = cal.getTime();

        Integer page = 1;
        Integer pageSize = 20;

        FoodOrderQueryResp resp = null;

        do {
            resp = antPlanetComplexApi.queryFoodOrder(page, pageSize, yesterday, now,  null,null, null, null);
            FoodOrderQueryResp.Data data = resp.getData();
            List<FoodOrderQueryResp.Data.ListItem> list = data.getList();



            list.forEach(item -> {
                String uid = item.getUid();
                String pf = item.getPf();
                String orderid = item.getOrderid();
                String storeid = item.getStoreid();
                String storename = item.getStorename();
                String storeaddress = item.getStoreaddress();
                Integer goodscount = item.getGoodscount();
                List<GoodsdataItem> goodsdata = item.getGoodsdata();
                Integer returncount = item.getReturncount();
                Integer status = item.getStatus();
                Integer isbalance = item.getIsbalance();
                String payprice = item.getPayprice();
                String price = item.getPrice();
                String returnprice = item.getReturnprice();
                String commission = item.getCommission();
                String phone = item.getPhone();
                String takecode = item.getTakecode();
                String qrdata = item.getQrdata();
                Integer closetime = item.getClosetime();
                String closetxt = item.getClosetxt();
                Integer createdtime = item.getCreatedtime();
                Integer updatedtime = item.getUpdatedtime();
                UserInfo userInfo = fetchUser(uid);
                PublisherOrderDtoBean o = fetchOrder(orderid);
                if (o.getId() == null) {
                    o.setFromInfo("antplanet");
                    o.setIsJifen(0);
                    o.setIsGif(0);
                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                    o.setBalance(0);
                    if(userInfo!=null){
                        o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                        o.setInvitation(userInfo.getInvitation());
                    }
                    o.setAdzone_id(109264550298L);
                    o.setAdzone_name(Config.BASE_NAME);
                    o.setOrder_type("蚂蚁星球");
                    o.setItem_num(Integer.valueOf(goodscount));
                    //商品图片
                o.setItem_img(goodsdata.get(0).getItemimage());
//                //商品标题
                    o.setItem_title(storename);
//                //订单编号
                    o.setTrade_id(orderid);
                    o.setTrade_parent_id(orderid);
//                //商品id
                    o.setItem_id("0");
//                //单个商品金额
                    o.setItem_price(price);
//                //设置佣金金额
                    o.setPub_share_pre_fee(commission);
//                //实际支付金额
                    o.setAlipay_total_price(payprice);
//                //订单支付时间
                    o.setTb_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //订单支付时间
                    o.setTk_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //处理订单状态3已结算12已付款13已失效
                    o.setTk_status(12);//处理已付款状态
                    //蚂蚁星球订单佣金结算状态0否1是
//                "status":,//状态 0-待付款，1-已付款，2-已付款充值中 ，3-充值完成，5-已结算10-订单关闭
                }else {
                    //                //订单支付时间
                    o.setTb_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
//                //订单支付时间
                    o.setTk_paid_time(DateFormatUtils.format(createdtime*1000l,"yyyy-MM-dd HH:mm:ss"));
                    if(!o.getPub_share_pre_fee().equals(commission) && userInfo!=null){
                        o.setPub_share_pre_fee(commission);
                        orderTask.getRate(o,userInfo, Float.parseFloat(commission),df,null);
                    }
                    //处理订单状态 这里处理已付款状态
                    if (status.equals(1)) {
                        o.setTk_status(12);
                    }else if(status.equals(5)){
                        o.setTk_status(3);
                    }else if(status.equals(10)){
                        o.setTk_status(13);
                    }
                }


                orderJpaRepository.save(o);

            });

            page++;
        } while (resp != null && !resp.getData().getFinish());


    }

    public void syncAntPlanetWphOrder() {
        DecimalFormat df = new DecimalFormat("#########.##");
        Calendar cal = Calendar.getInstance();
        //此时此刻
        Date now = cal.getTime();
        //定位到上一个小时，唯品会只允许1个小时
//        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.add(Calendar.MINUTE, -59);
//        cal.set(Calendar.SECOND, 0);
//        cal.set(Calendar.MILLISECOND, 0);
//        cal.add(Calendar.DATE, -10);
        Date lastHour = cal.getTime();

        Integer page = 1;
        //唯品会最高要求100
        Integer pageSize = 100;

        WphOrderQueryResp resp = null;

            resp = antPlanetComplexApi.queryWphOrder(page, pageSize, lastHour, now);
            WphOrderQueryResp.Data data = resp.getData();
            List<WphOrderQueryResp.Data.OrderinfolistItem> list = data.getOrderinfolist();
            list.forEach(item -> {
                String ordersn = item.getOrdersn();
                Integer status = item.getStatus();
                Integer newcustomer = item.getNewcustomer();
                String uid = item.getChanneltag();
                Long ordertime = item.getOrdertime();
                Object signtime = item.getSigntime();
                Object settledtime = item.getSettledtime();
                List<DetaillistItem> detaillist = item.getDetaillist();
                Long lastupdatetime = item.getLastupdatetime();
                Integer settled = item.getSettled();
                Integer selfbuy = item.getSelfbuy();
                String ordersubstatusname = item.getOrdersubstatusname();
                String commission = item.getCommission();
                Object aftersalechangecommission = item.getAftersalechangecommission();
                Object aftersalechangegoodscount = item.getAftersalechangegoodscount();
                Long commissionentertime = item.getCommissionentertime();
                String ordersource = item.getOrdersource();
                String pid = item.getPid();
                Integer isprepay = item.getIsprepay();
                String statparam = item.getStatparam();
                Integer issplit = item.getIssplit();
                Object parentsn = item.getParentsn();
                Integer ordertrackreason = item.getOrdertrackreason();
                String appkey = item.getAppkey();

                UserInfo userInfo = fetchUser(uid);
                PublisherOrderDtoBean o = fetchOrder(ordersn);
                if (o.getId() == null) {
                    o.setFromInfo("antplanet");
                    o.setIsJifen(0);
                    o.setIsGif(0);
                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                    o.setBalance(0);
                    if(userInfo!=null){
                        o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                        o.setInvitation(userInfo.getInvitation());
                    }
                    o.setAdzone_id(109264550298L);
                    o.setAdzone_name(Config.BASE_NAME);
                    o.setOrder_type("唯品会");
                    o.setItem_num(Integer.valueOf(detaillist.size()));
                    //商品图片
                    o.setItem_img(detaillist.get(0).getGoodsthumb());
//                //商品标题
                    o.setItem_title(detaillist.get(0).getGoodsname());
//                //订单编号
                    o.setTrade_id(ordersn);
                    o.setTrade_parent_id(ordersn);
//                //商品id
                    o.setItem_id(String.valueOf(detaillist.get(0).getGoodsid()));
//                //单个商品金额
                    String commissiontotalcost = detaillist.get(0).getCommissiontotalcost();
                    o.setItem_price(commissiontotalcost);
//                //设置佣金金额
                    String commi = detaillist.get(0).getCommission();
                    o.setPub_share_pre_fee(commi);
//                //实际支付金额
                    o.setAlipay_total_price(String.valueOf((Double.parseDouble(commissiontotalcost)*100-Double.parseDouble(commi)*100)/100));
//                //订单支付时间
                    o.setTb_paid_time(DateFormatUtils.format(new Date(ordertime),"yyyy-MM-dd HH:mm:ss"));
//                //订单支付时间
                    o.setTk_paid_time(DateFormatUtils.format(new Date(ordertime),"yyyy-MM-dd HH:mm:ss"));
//                //处理订单状态3已结算12已付款13已失效
                    o.setTk_status(12);//处理已付款状态
                    //蚂蚁星球订单佣金结算状态0否1是
//                "status":,//状态 0-待付款，1-已付款，2-已付款充值中 ，3-充值完成，5-已结算10-订单关闭
                }else {
                    if(!o.getPub_share_pre_fee().equals(commission) && userInfo!=null){
                        o.setPub_share_pre_fee(commission);
                        orderTask.getRate(o,userInfo, Float.parseFloat(commission),df,null);
                    }
                    //处理订单状态 这里处理已付款状态
                    if (status.equals(1)) {
                        o.setTk_status(12);
                    }else if(status.equals(5)){
                        o.setTk_status(3);
                    }else if(status.equals(10)){
                        o.setTk_status(13);
                    }
                }
                orderJpaRepository.save(o);

            });



    }
    private PublisherOrderDtoBean fetchOrder(String orderid){
        PublisherOrderDtoBean publisherOrderDtoBean;
        try {
            publisherOrderDtoBean = orderRepository.findByRelationIdCount(orderid);
        } catch (Exception e) {
            //当发现有多个订单时 删除重复的订单
            List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(orderid);
            for (int j = 1; j < publisherOrderDtoBeans.size(); j++) {
                orderJpaRepository.deleteById(publisherOrderDtoBeans.get(j).getId());
            }
            publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
        }
        if(publisherOrderDtoBean==null){
            publisherOrderDtoBean = new PublisherOrderDtoBean();
        }
        return publisherOrderDtoBean;
    }
    private UserInfo fetchUser(String uid){
        UserInfo userInfo=null;
        if(StringUtils.isNotEmpty(uid)){
            userInfo=userRepository.getUserByRelationId(uid);
        }
        return userInfo;
    }


}
